package com.cgq.utils;

import com.cgq.pro.entity.Generator;
import com.cgq.pro.service.GeneratorService;

/**
 * 主键生成工具
 * @author chenkaile
 *
 */
public class IdGenerator {
	
	/**
	 * 生成主键
	 * @param tableName 表名称
	 * @param prefix 前缀
	 * @param length 主键长度
	 * @return
	 */
	public static String getId(GeneratorService service,String tableName,String prefix,int length){
		Generator entity=service.findByTableName(tableName,prefix);
		if(entity==null){
			entity=new Generator();
			entity.setTableName(tableName);
			entity.setValue(generatorValue(prefix, length,1));
			service.save(entity);
		}else{
			int value=Integer.parseInt(entity.getValue().replace(prefix, ""))+1;
			entity.setValue(generatorValue(prefix, length,value));
			service.update(entity);
		}
		
		return entity.getValue();
	}
	
	private static String generatorValue(String prefix,int length,int value){
		StringBuilder newValue=new StringBuilder();
		newValue.append(prefix);
		int size=(prefix+value).length();
		for (int i = 0; i < length-size; i++) {
			newValue.append("0");
		}
		newValue.append(value);
		return newValue.toString();
	}
}
